package org.mall.modules.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/***
 *@author yinxucun
 *@date 2019-11-12 18:03 
 */
@Service
public class SMSServiceImpl {

    @Value("${mall.params.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${mall.params.sms.accessSecret}")
    private String accessSecret;

    @Value("${mall.params.sms.signName}")
    private String signName;

    @Value("${mall.params.sms.regionId}")
    private String regionId;



    private static SmsClient client;

    private SmsClient getClient(){
        if (client==null){
            client=new SmsClient(DefaultProfile.getProfile(this.regionId,this.accessKeyId,this.accessSecret));
        }
        return client;
    }

    public boolean sendMessage(String mobile , String templateId,String content){
        CommonRequest request=new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setAction("SendSms");
        request.putBodyParameter("PhoneNumber",mobile);
        request.putBodyParameter("SignName",this.signName);
        request.putBodyParameter("TemplateCode",templateId);
        request.putBodyParameter("TemplateParam",content);
        try {
            CommonResponse response= getClient().getCommonResponse(request);
            return "OK".equals(JSONObject.parseObject(response.getData()).get("CODE"));
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static class SmsClient  extends DefaultAcsClient {
        SmsClient(DefaultProfile defaultProfile) {
            super(defaultProfile);
        }
    }
}
